Page({
  data: {
    isMerchantLoggedIn: false,
    merchantId: "",
    password: "",
    merchantInfo: {
      id: "",
      name: "",
      avatar: "/images/default_avatar.png",
    },
  },

  onLoad() {
    // 检查商家登录状态
    const merchantToken = wx.getStorageSync("merchantToken");
    if (merchantToken) {
      this.setData({
        isMerchantLoggedIn: true,
        merchantInfo:
          wx.getStorageSync("merchantInfo") || this.data.merchantInfo,
      });
    }
  },

  onInputMerchantId(e) {
    this.setData({ merchantId: e.detail.value });
  },

  onInputPassword(e) {
    this.setData({ password: e.detail.value });
  },

  handleMerchantLogin() {
    const { merchantId, password } = this.data;
    if (!merchantId || !password) {
      wx.showToast({
        title: "请填写完整信息",
        icon: "none",
      });
      return;
    }

    // TODO: 实现商家登录逻辑
    wx.showLoading({
      title: "登录中...",
    });

    // 模拟登录请求
    setTimeout(() => {
      wx.hideLoading();
      // 存储商家登录状态
      wx.setStorageSync("merchantToken", "dummy-merchant-token");
      wx.setStorageSync("merchantInfo", {
        id: merchantId,
        name: "示例商家",
        avatar: "/images/default_avatar.png",
      });

      this.setData({
        isMerchantLoggedIn: true,
        merchantInfo: {
          id: merchantId,
          name: "示例商家",
          avatar: "/images/default_avatar.png",
        },
      });

      wx.showToast({
        title: "登录成功",
        icon: "success",
      });
    }, 1500);
  },

  showRegisterInfo() {
    wx.showModal({
      title: "商家入驻",
      content: "请联系管理员申请商家入驻，联系电话：123-4567-8900",
      showCancel: false,
    });
  },

  navigateToMenu() {
    wx.navigateTo({
      url: "/pages/merchant/menu/menu",
    });
  },

  navigateToOrders() {
    wx.navigateTo({
      url: "/pages/merchant/orders/orders",
    });
  },

  navigateToAnalytics() {
    wx.navigateTo({
      url: "/pages/merchant/analytics/analytics",
    });
  },

  navigateToSettings() {
    wx.navigateTo({
      url: "/pages/merchant/settings/settings",
    });
  },

  handleLogout() {
    wx.showModal({
      title: "提示",
      content: "确定要退出登录吗？",
      success: (res) => {
        if (res.confirm) {
          // 清除商家登录状态
          wx.removeStorageSync("merchantToken");
          wx.removeStorageSync("merchantInfo");

          this.setData({
            isMerchantLoggedIn: false,
            merchantId: "",
            password: "",
            merchantInfo: {
              id: "",
              name: "",
              avatar: "/images/default_avatar.png",
            },
          });

          wx.showToast({
            title: "已退出登录",
            icon: "success",
          });
        }
      },
    });
  },
});
